package org.mobicents.servlet.sip.example;

import java.io.IOException;
import java.io.PrintWriter;


import java.util.concurrent.CopyOnWriteArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WebServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

		
		request.setAttribute("uzytkownicy", AdressBook.getList());
		
		CopyOnWriteArrayList<CUser> adressBook= AdressBook.getList();
		
		CopyOnWriteArrayList<String> groups = new CopyOnWriteArrayList<String>();
		
		for (CUser cUser : adressBook) {
			if(!groups.contains(cUser.getIp())) {
				groups.add(cUser.getIp());
			}
		}
		request.setAttribute("grupy", groups);
		
		CopyOnWriteArrayList<CMessage> messages = CDispatcher.getInstance().getMessageList();
		request.setAttribute("wiadomosci", messages);
		
		request.getRequestDispatcher("/index.jsp").forward(request, response);		
		
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//String message = request.getAttribute("message").toString();
		System.out.println("----doPost----");
		String message = request.getParameter("message");
		PrintWriter out = response.getWriter();
		String selectedGroup = request.getParameter("groupSelected");
		String godzina = request.getParameter("godzina");
		String minuta = request.getParameter("minuta");
		
		System.out.println("----doPost2---- godzina " + godzina + " minuty " + minuta + " selectedGroup " + selectedGroup);
		
		String time; 
		
		if(godzina.contains("-")) 
		{
			time = "instant";
			System.out.println("wysylam od razu");
		}
		else
		{
			time = godzina + ":" + minuta + ":00";
			System.out.println("wysylam za jakis czas");
		}

		///stworz liste odbiorcow na podstawie IP
		CopyOnWriteArrayList<CUser> cUsers = AdressBook.getList();
		CopyOnWriteArrayList<CUser> receivers = new CopyOnWriteArrayList<CUser>();
		
		for (CUser cUser : cUsers) {
			if(cUser.getIp().equals(selectedGroup) || selectedGroup.equals("all")) 
			{	
				receivers.add(cUser);
			}
		}
		//dodaj do kolejki wysylania
		if(!receivers.isEmpty())
			CDispatcher.getInstance().addMessageToList(new CMessage(time, receivers, message));	
		
		
		// wracaj do stronki
		response.sendRedirect(response.encodeRedirectURL("/call-blocking-1.7.0-SNAPSHOT/WebServlet"));
	}
}
